<?php

namespace App\Repositories;

use App\Models\Order;
use Illuminate\Database\Eloquent\Collection;

class OrderRepository extends BaseRepository
{
    public function __construct(Order $model)
    {
        parent::__construct($model);
    }

    /**
     * 根据order_id查找订单
     */
    public function findByOrderId(string $orderId): ?Order
    {
        return $this->model->where('order_id', $orderId)->first();
    }

    /**
     * 获取房间的所有订单
     */
    public function getByRoom(int $roomId): Collection
    {
        return $this->model->where('room_id', $roomId)
            ->with('user')
            ->orderBy('created_at', 'desc')
            ->get();
    }

    /**
     * 获取用户的订单
     */
    public function getByUser(int $userId): Collection
    {
        return $this->model->where('user_id', $userId)
            ->with('room')
            ->orderBy('created_at', 'desc')
            ->get();
    }

    /**
     * 获取房间用户的订单
     */
    public function getByRoomAndUser(int $roomId, int $userId): ?Order
    {
        return $this->model->where('room_id', $roomId)
            ->where('user_id', $userId)
            ->first();
    }

    /**
     * 根据状态获取订单
     */
    public function getByStatus(string $status): Collection
    {
        return $this->model->where('status', $status)->get();
    }

    /**
     * 获取待确认订单
     */
    public function getPendingOrders(): Collection
    {
        return $this->getByStatus('pending');
    }

    /**
     * 获取已确认订单
     */
    public function getConfirmedOrders(): Collection
    {
        return $this->getByStatus('confirmed');
    }

    /**
     * 获取已取消订单
     */
    public function getCancelledOrders(): Collection
    {
        return $this->getByStatus('cancelled');
    }

    /**
     * 确认订单
     */
    public function confirm(int $orderId): bool
    {
        return $this->update($orderId, ['status' => 'confirmed']);
    }

    /**
     * 取消订单
     */
    public function cancel(int $orderId): bool
    {
        return $this->update($orderId, ['status' => 'cancelled']);
    }

    /**
     * 完成订单
     */
    public function complete(int $orderId): bool
    {
        return $this->update($orderId, ['status' => 'completed']);
    }

    /**
     * 获取房间订单统计
     */
    public function getRoomStats(int $roomId): array
    {
        $orders = $this->getByRoom($roomId);
        
        return [
            'total_orders' => $orders->count(),
            'pending_orders' => $orders->where('status', 'pending')->count(),
            'confirmed_orders' => $orders->where('status', 'confirmed')->count(),
        ];
    }
}
